import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import Cookies from 'js-cookie'
import { login as loginApi, logout as logoutApi, getProfile } from '@/api/auth'
import type { User, LoginRequest } from '@/types'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string>(Cookies.get('token') || '')
  const user = ref<User | null>(null)
  const loading = ref(false)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value && !!user.value)
  const isAdmin = computed(() => false) // 暂时返回false，后续需要实现角色检查

  // 登录
  const login = async (loginData: LoginRequest) => {
    loading.value = true
    try {
      const response = await loginApi(loginData);
      const { token: newToken, user: userData } = response.data
      
      token.value = newToken
      user.value = userData
      
      // 保存token到cookie
      Cookies.set('token', newToken, { expires: 7 })
      
      return response
    } catch (error) {
      throw error
    } finally {
      loading.value = false
    }
  }

  // 登出
  const logout = async () => {
    try {
      await logoutApi()
    } catch (error) {
      console.error('登出失败:', error)
    } finally {
      // 清除状态
      token.value = ''
      user.value = null
      
      // 清除cookie
      Cookies.remove('token')
    }
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    if (!token.value) return
    
    loading.value = true
    try {
      const response = await getProfile();
      user.value = response.data
      return response
    } catch (error) {
      // 如果获取用户信息失败，清除token
      token.value = ''
      user.value = null
      Cookies.remove('token')
      throw error
    } finally {
      loading.value = false
    }
  }

  // 更新用户信息
  const updateUser = (userData: User) => {
    user.value = userData
  }

  // 初始化用户状态
  const initUser = async () => {
    if (token.value && !user.value) {
      await fetchUserInfo()
    }
  }

  return {
    // 状态
    token,
    user,
    loading,
    
    // 计算属性
    isLoggedIn,
    isAdmin,
    
    // 方法
    login,
    logout,
    fetchUserInfo,
    updateUser,
    initUser
  }
}) 